package com.automation.entity;
import com.automation.service.AppiumUtils;
import com.automation.service.ImageUtils;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class ReviewPage extends BasePage {
    private final By moreButton = By.xpath("//*[@text='查看更多评价']");
    private final By mediaTag = By.xpath("//*[contains(@text, '带图') or contains(@text, '视频')]");
    private final By reviewItem = By.id("com.dianping.v1:id/review_item");
    private final By backButton = By.xpath("//android.widget.ImageButton[@content-desc='返回']");

    public ReviewPage(AndroidDriver driver) {
        super(driver);
    }

    public void viewMoreReviews() {
        click(moreButton);
    }

    public boolean hasMediaReviews() {
        return AppiumUtils.isElementPresent(driver, mediaTag, 5);
    }

    public List<String> captureHighQualityImages() throws IOException {
        List<String> savedImages = new ArrayList<>();
        List<WebElement> reviews = driver.findElements(reviewItem);

        for (int i = 0; i < reviews.size(); i++) {
            try {
                WebElement imageContainer = reviews.get(i)
                        .findElement(By.id("com.dianping.v1:id/review_images_container"));

                if (imageContainer.isDisplayed()) {
                    File screenshot = imageContainer.getScreenshotAs(OutputType.FILE);
                    Path dest = Paths.get("screenshots/review_" + System.currentTimeMillis() + ".png");
                    Files.copy(screenshot.toPath(), dest);

                    if (ImageUtils.isHighQuality(dest.toFile())) {
                        savedImages.add(dest.toString());
                    }
                }
            } catch (Exception e) {
                // 忽略没有图片的评论
            }
        }
        return savedImages;
    }

    public void navigateBack() {
        click(backButton);
    }
}